import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Typography,
  Chip,
  Alert,
  CircularProgress,
  Tabs,
  Tab,
  Card,
  CardMedia,
  IconButton,
  Grid,
} from '@mui/material';
import {
  Edit,
  Save,
  Cancel,
  Delete,
  Add,
  Image,
  VideoFile,
} from '@mui/icons-material';
import { Content, ContentType, UpdateContentTextRequest, ContentImage } from '../../../types';
import { useContent } from '../../../hooks/useContent';
import { MediaUploader } from './MediaUploader';
import { ImageManager } from './ImageManager';
import { VideoManager } from './VideoManager';

interface ContentEditorProps {
  open: boolean;
  content: Content | null;
  onClose: () => void;
  onUpdate: (updatedContent: Content) => void;
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`content-editor-tabpanel-${index}`}
    >
      {value === index && <Box sx={{ pt: 2 }}>{children}</Box>}
    </div>
  );
};

export const ContentEditor: React.FC<ContentEditorProps> = ({
  open,
  content,
  onClose,
  onUpdate,
}) => {
  const { updateContentText, updateCover, updateImages, updateVideo, loading } = useContent();
  const [currentTab, setCurrentTab] = useState(0);
  const [formData, setFormData] = useState({
    title: '',
    textContent: '',
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // 初始化表单数据
  useEffect(() => {
    if (content) {
      setFormData({
        title: content.title || '',
        textContent: content.textContent || '',
      });
      setCurrentTab(0);
      setError(null);
      setSuccess(null);
    }
  }, [content]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  const handleInputChange = (field: keyof typeof formData) => (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value,
    }));
  };

  const handleUpdateText = async () => {
    if (!content) return;

    try {
      setError(null);
      const updateData: UpdateContentTextRequest = {
        title: formData.title.trim(),
        textContent: formData.textContent.trim(),
      };

      await updateContentText(content.id, updateData);
      setSuccess('文本内容更新成功');
      
      // 更新本地内容数据
      const updatedContent = {
        ...content,
        ...updateData,
        updatedAt: new Date().toISOString(),
      };
      onUpdate(updatedContent);
    } catch (err) {
      setError('更新失败，请稍后重试');
    }
  };

  const handleCoverUpdate = async (file: File) => {
    if (!content) return;

    try {
      setError(null);
      await updateCover(content.id, { cover: file });
      setSuccess('封面更新成功');
      
      // 这里应该重新获取内容信息以获取新的封面URL
      // 为了简化，我们只显示成功消息
    } catch (err) {
      setError('封面更新失败，请稍后重试');
    }
  };

  const handleImagesUpdate = async (deleteIds: string[], newImages: File[]) => {
    if (!content) return;

    try {
      setError(null);
      await updateImages(content.id, {
        deleteImageIds: deleteIds.join(','),
        newImages,
      });
      setSuccess('图片更新成功');
    } catch (err) {
      setError('图片更新失败，请稍后重试');
    }
  };

  const handleVideoUpdate = async (file: File) => {
    if (!content) return;

    try {
      setError(null);
      await updateVideo(content.id, { video: file });
      setSuccess('视频更新成功');
    } catch (err) {
      setError('视频更新失败，请稍后重试');
    }
  };

  const handleClose = () => {
    setError(null);
    setSuccess(null);
    onClose();
  };

  if (!content) return null;

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: { minHeight: '70vh' }
      }}
    >
      <DialogTitle>
        <Box display="flex" alignItems="center" gap={1}>
          <Edit />
          <Typography variant="h6">编辑内容</Typography>
          <Chip
            label={content.contentType === ContentType.IMAGE ? '图文' : '视频'}
            color={content.contentType === ContentType.IMAGE ? 'primary' : 'secondary'}
            size="small"
          />
        </Box>
      </DialogTitle>

      <DialogContent dividers>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
            {error}
          </Alert>
        )}
        
        {success && (
          <Alert severity="success" sx={{ mb: 2 }} onClose={() => setSuccess(null)}>
            {success}
          </Alert>
        )}

        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={currentTab} onChange={handleTabChange}>
            <Tab label="基本信息" />
            <Tab label="封面" />
            {content.contentType === ContentType.IMAGE && <Tab label="图片管理" />}
            {content.contentType === ContentType.VIDEO && <Tab label="视频管理" />}
          </Tabs>
        </Box>

        <TabPanel value={currentTab} index={0}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <TextField
              fullWidth
              label="标题"
              value={formData.title}
              onChange={handleInputChange('title')}
              placeholder="请输入内容标题"
              variant="outlined"
            />
            
            <TextField
              fullWidth
              label="内容描述"
              value={formData.textContent}
              onChange={handleInputChange('textContent')}
              placeholder="请输入内容描述"
              multiline
              rows={6}
              variant="outlined"
            />

            <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
              <Button
                variant="contained"
                startIcon={<Save />}
                onClick={handleUpdateText}
                disabled={loading}
              >
                {loading ? <CircularProgress size={20} /> : '保存文本'}
              </Button>
            </Box>
          </Box>
        </TabPanel>

        <TabPanel value={currentTab} index={1}>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Typography variant="h6">当前封面</Typography>
            {content.coverUrl && (
              <Card sx={{ maxWidth: 300 }}>
                <CardMedia
                  component="img"
                  height="200"
                  image={content.coverUrl}
                  alt="当前封面"
                />
              </Card>
            )}
            
            <MediaUploader
              accept="image/*"
              onUpload={handleCoverUpdate}
              loading={loading}
              buttonText="上传新封面"
              helperText="支持 JPG、PNG 格式，建议尺寸 16:9"
            />
          </Box>
        </TabPanel>

        {content.contentType === ContentType.IMAGE && (
          <TabPanel value={currentTab} index={2}>
            <ImageManager
              contentId={content.id}
              currentImages={content.images || []}
              onUpdate={handleImagesUpdate}
              loading={loading}
            />
          </TabPanel>
        )}

        {content.contentType === ContentType.VIDEO && (
          <TabPanel value={currentTab} index={2}>
            <VideoManager
              contentId={content.id}
              currentVideos={content.videoUrls}
              onUpdate={handleVideoUpdate}
              loading={loading}
            />
          </TabPanel>
        )}
      </DialogContent>

      <DialogActions>
        <Button onClick={handleClose} startIcon={<Cancel />}>
          关闭
        </Button>
      </DialogActions>
    </Dialog>
  );
}; 